<template>
  <div>
    <!-- 右边基本表格 -->
    <BasicTable @register="registerTable">
      <!-- 表格标题 -->
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ title }} </span>
      </template>
      <!-- 表格右上角自定义按钮（新增...） -->
      <template #toolbar>
        <a-button
          v-for="(item, index) in butData"
          :key="index"
          :type="item.btnType"
          @click="item.do"
          v-auth="item.auth"
        >
          <Icon :icon="item.icon" /> {{ t(item.title) }}
        </a-button>
      </template>
      <!-- 表格插槽 -->
      <template #djNo="{ record }">
        <a @click="handleForm({ djNo: record.djNo })">
          {{ record.djNo }}
        </a>
      </template>
    </BasicTable>
    <!-- 打印 -->
    <PrintModal @register="registerModal" @success="handleSuccess" />
    <FormTabs @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsM8OrderFlowCheckCheckDealList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, onMounted, ref, watch } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable, ActionItem } from '/@/components/Table';
  import { customListData,listSet } from '/@/api/layout/layout';
  import { useDrawer } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { FormProps } from '/@/components/Form';
  import { schemasData, tabConfigData } from '/@/utils/custom';
  import PrintModal from '/@/components/print/printModal.vue';
  import FormTabs from './formTabs.vue';
  import { handleExport } from '/@/utils/export';
  import { m8OperCheckDelDelete, stageConfirm } from '/@/api/m8/order/m8OperCheckDel';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';

  const { t } = useI18n('test.testData');
  const { showMessage } = useMessage();
  const { ctxPath } = useGlobSetting();

  //配置表单内容
  const searchForm = ref<FormProps>({
    baseColProps: { lg: 6, md: 8 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    schemas: [],
    fieldMapToTime: [
      ['operCheck.createDate', ['operCheck.createDate_gte', 'operCheck.createDate_lte']],
    ],
  });
  let tableColumns = ref<any>([]);
  let butData = ref<any>([]);
  let actionColumnData = ref<ActionItem[]>([]);
  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});
  const getTitle = ref({
    // 表格标题图标
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: listTabConfig.value.title,
  });
  let title = ref('');
  const props = defineProps({
    ope: { type: String, default: '' },
  });
  watch(
    () => props.ope,
    () => {
      reload();
    },
  );
  const actionColumn: BasicColumn = {
    width: 250, //操作按钮宽度
    align: 'left',
    actions: (record: Recordable) => [
      {
        icon: 'i-clarity:note-edit-line',
        title: t('编辑'),
        onClick: handleForm.bind(this, { djNo: record.djNo, ope: 0 }),
        auth: 'check:m8OperCheckDel:edit',
        ifShow: record.dealStatus != 4 ? true : false,
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: t('删除'),
        popConfirm: {
          title: t('是否确认删除发料单'),
          confirm: handleDelete.bind(this, { id: record.djno }),
        },
        auth: 'check:m8OperCheckDel:edit',
        ifShow: record.dealStatus == 2 ? true : false,
      },
      {
        icon: 'simple-line-icons:check',
        color: 'success',
        label: '方案确认',
        title: t('方案确认'),
        popConfirm: {
          title: t('是否确认进行【方案确认】'),
          confirm: handleStageConfirm.bind(this, { djNo: record.djNo, ope: 3 }),
        },
        auth: 'check:m8OperCheckDel:edit',
        ifShow: record.dealStatus == 2 ? true : false,
      },
      {
        icon: 'simple-line-icons:action-undo',
        color: 'warning',
        label: '撤销方案',
        title: t('撤销方案'),
        popConfirm: {
          title: t('是否确认进行【撤销方案】'),
          confirm: handleStageConfirm.bind(this, { djNo: record.djNo, ope: 2 }),
        },
        auth: 'check:m8OperCheckDel:edit',
        ifShow: record.dealStatus == 3 ? true : false,
      },
      {
        icon: 'simple-line-icons:check',
        color: 'success',
        label: '结果确认',
        title: t('结果确认'),
        popConfirm: {
          title: t('是否确认进行【结果确认】'),
          confirm: handleStageConfirm.bind(this, { djNo: record.djNo, ope: 4 }),
        },
        auth: 'check:m8OperCheckDel:edit',
        ifShow: record.dealStatus == 3 ? true : false,
      },
      {
        icon: 'simple-line-icons:action-undo',
        color: 'warning',
        label: '撤销结果',
        title: t('撤销结果'),
        popConfirm: {
          title: t('是否确认进行【撤销结果】'),
          confirm: handleStageConfirm.bind(this, { djNo: record.djNo, ope: 0 }),
        },
        auth: 'check:m8OperCheckDel:edit',
        ifShow: record.dealStatus == 4 ? true : false,
      },
    ],
  };
  onMounted(async () => {
    const res = await listSet({ viewCode: 'M8_oper_check_del_list' });
    title.value = res.layVoucherView.name;
    layVoucherView.value = res.layVoucherView;

    searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);

    tableColumns.value = layVoucherView.value.flistTabCols; //表格表头

    butData.value = layVoucherView.value.headBtns; //表格右上角按钮
    butData.value.forEach((item) => {
      if (item.btnKey === 'btnPrint') {
        item.do = () => handlePrint();
      }
      if (item.btnKey === 'btnExport') {
        //item.do = () => btnExport('/check/m8OperCheckDel/exportData');
        item.do = () => handleExportData();
      }
    });

    actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮

    listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
    setProps({
      api: customListData,
      beforeFetch: (params) => {
        params.url = listTabConfig.value.api;
        params.operatorSubDate_gte = params.operatorSubDate ? params.operatorSubDate[0] : '';
        params.operatorSubDate_lte = params.operatorSubDate ? params.operatorSubDate[1] : '';
        params.dealResultSunDate_gte = params.dealResultSunDate ? params.dealResultSunDate[0] : '';
        params.dealResultSunDate_lte = params.dealResultSunDate ? params.dealResultSunDate[1] : '';
        params.lastSubCheckDate_gte = params.lastSubCheckDate ? params.lastSubCheckDate[0] : '';
        params.lastSubCheckDate_lte = params.lastSubCheckDate ? params.lastSubCheckDate[1] : '';
        params.operatorSubDate = '';
        params.dealResultSunDate = '';
        params.lastSubCheckDate = '';
        params.ope = props.ope;
        return params;
      },
      autoCreateKey: listTabConfig.value.autoCreateKey,
      bordered: listTabConfig.value.bordered,
      canResize: listTabConfig.value.canResize,
      clearSelectOnPageChange: listTabConfig.value.clearSelectOnPageChange,
      clickToRowSelect: listTabConfig.value.clickToRowSelect,
      ellipsis: listTabConfig.value.ellipsis,
      emptyDataIsShowTable: listTabConfig.value.emptyDataIsShowTable,
      inset: listTabConfig.value.inset,
      isTreeTable: listTabConfig.value.isTreeTable,
      pagination: listTabConfig.value.pagination,
      showIndexColumn: listTabConfig.value.showIndexColumn,
      showSummary: listTabConfig.value.showSummary,
      showTableSetting: listTabConfig.value.showTableSetting,
      striped: listTabConfig.value.striped,
      useSearchForm: listTabConfig.value.useSearchForm,
      tableSetting: listTabConfig.value.tableSetting,
      titleHelpMessage: listTabConfig.value.titleHelpMessage,
      maxHeight: listTabConfig.value.maxHeight,
      resizeHeightOffset: listTabConfig.value.resizeHeightOffset,
      rowSelection: {
        type: 'checkbox',
      },
    });
    if (!listTabConfig.value.immediate) {
      reload();
    }
  });

  const [registerModal, { openModal }] = useModal();
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, setProps, getSelectRows, getForm }] = useTable({
    actionColumn: actionColumn,
    columns: tableColumns,
    formConfig: searchForm.value as FormProps,
  });

  // 刷新表格数据（含表单回调）
  function handleSuccess() {
    reload();
  }

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  function handleOpe(record) {
    openDrawer(true, record);
  }

  // 删除
  async function handleDelete(record: Recordable) {
    const res = await m8OperCheckDelDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  async function handleStageConfirm(record: Recordable) {
    const res = await stageConfirm(record);
    showMessage(res.message);
    handleSuccess();
  }

  // 打印
  const handlePrint = () => {
    let rows = getSelectRows();
    if (rows.length <= 0) {
      showMessage('请至少选择一条要打印的数据!');
    } else {
      let ids = '';
      rows.map((item) => {
        if (ids == '') {
          ids = item.id;
        } else {
          ids = ids + ',' + item.id;
        }
      });
      let obj = {
        title: '不良品处理单打印',
        ids: ids,
        height: '0.9',
        width: '0.9',
        fileName: 'printCheckDeal',
      };
      openModal(true, obj);
    }
  };

  //导出数据
  function btnExport() {
    var formdata = getForm().getFieldsValue();
    formdata = { ...formdata, ...props };
    handleExport('/check/m8OperCheckDel/exportData', formdata);
  }

  // 报表方式导出
  async function handleExportData() {
    let searchForm = getForm().getFieldsValue();
    for (const key in searchForm) {
      if (Array.isArray(searchForm[key])) {
        searchForm[key + '_gte'] = searchForm[key][0];
        searchForm[key + '_lte'] = searchForm[key][1];
        delete searchForm[key];
      }
    }
    // 将 undefined 值替换为 ''
    const filtereSearchForm = Object.fromEntries(
      Object.entries(searchForm).map(([key, value]) => [key, value === undefined ? '' : value]),
    );
    let formdata = {
      ...filtereSearchForm,
      ope: props.ope ? props.ope : '',
    };
    console.log(formdata);
    const params = new URLSearchParams(formdata).toString();
    downloadByUrl({
      url:
        ctxPath +
        `/ureport/excel?_u=file:export_oper_check_del.ureport.xml&_n=不良品处理&${params}`,
    });
  }
</script>
<style>
  .jeesite-editable-cell__action {
    display: none;
  }

  .edit-cell-align-center {
    width: 100% !important;
  }
</style>
